const utils = require("self-utils");
const db = uniCloud.database();
const cmd = db.command;
module.exports = {
	_before: async function() { // 通用预处理器
		this.userInfo = await utils.getUserInfo(this);
		if (!this.userInfo.uid) throw this.userInfo;
	},
	// 创建订单
	async createOrder(data) {
		data.user_id = this.userInfo.uid;
		data.order_no = getOrderId();
		data.out_trade_no = data.order_no + "_" + String(Math.random()).substring(3, 9) //进行拿插件支付单号（唯一）
		await db.collection("kt-mall-order").add(data)
		return {
			order_no: data.order_no,
			out_trade_no: data.out_trade_no
		};
	},
	//获取订单列表
	async getList(pageNum = 1) {
		let pageSize = 10;
		pageNum = (pageNum - 1) * pageSize;
		return await db.collection("kt-mall-order").where({
			user_id: this.userInfo.uid,
			status: cmd.neq(0)
		}).limit(pageSize).skip(pageNum).orderBy("createTime", "desc").get()
	},
	//获取订单详情
	async getRow(id) {
		return await db.collection("kt-mall-order").where({
			_id: id
		}).get()
	},
	//管理员根据订单状态获取所有的订单
	async getAllList(pageNum = 1, done) {
		let pageSize = 10;
		pageNum = (pageNum - 1) * pageSize;
		if (!this.userInfo.role.includes('manage')) return {
			msg: "没有权限",
			code: -1
		};
		return await db.collection("kt-mall-order").where({
			status: cmd.neq(0),
			done: done
		}).limit(pageSize).skip(pageNum).orderBy("createTime", "desc").get()
	},
	//管理员修改订单状态以及上传物流单号
	async updateDone(id, wuliuOrder) {
		if (!this.userInfo.role.includes('manage')) return {
			msg: "没有权限",
			code: -1
		};
		return await db.collection("kt-mall-order").doc(id).update({
			done: true,
			wuliuOrder: wuliuOrder
		})
	},
	//管理员修改订单状态为退款并且完成订单
	async updateDoneTui(id) {
		if (!this.userInfo.role.includes('manage')) return {
			msg: "没有权限",
			code: -1
		};
		return await db.collection("kt-mall-order").doc(id).update({
			done: true,
			status: 3
		})
	},
	async _timing() {
		let time = Date.now() - 3600 * 1000 * 3
		await db.collection("kt-mall-order").where({
			status: 0,
			createTime: cmd.lt(time)
		}).remove()
	}

}

// 生成订单号-主要进行时间戳以及随机号拼接
function getOrderId() {
	return Date.now() + "_" + String(Math.random()).substring(3, 9)
}